"""
@author: dysb
@file: homework3.py
@time: 2024/8/25 21:42
"""
import pymysql
import redis
import json
import ast
from functools import wraps
# 连接mysql
db = pymysql.connect(
    user = "deco",
    password = "deco123",
    host = "192.168.186.136",
    database = "sc"
)
cursor = db.cursor()

# 连接redis
r = redis.Redis(host='192.168.186.136', port=6379, db=0)

# 将信息存入redis中
def setInfo_redis(key,tup):
    tuple_data = tup[0]
    serialized_data = json.dumps(tuple_data)
    r.set(key,serialized_data)


# 写一个获取用户信息的函数，这个函数接受一个name
# def getInfo(name):
#     pass
# 写一个缓存装饰器
#       name 作为redis的key
#       先去redis里找对应的人员信息
#       如果存在，直接返回
#       如果不存在，就去数据库获取，获取到的信息再写入redis
def cache(func):
    @wraps(func)
    def inner(name,*args,**kwargs):
        key = f"{name}"
        if r.exists(key) == 1:
            value = r.get(key).decode('utf-8')
            tuple_data = ast.literal_eval(value)
            print(f"ID:{tuple_data[0]} 姓名:{tuple_data[1]} 年龄:{tuple_data[2]} 住址:{tuple_data[3]}")
        else:
            tuple_data = func(name,*args,**kwargs)
            # ((1, 'sc', 10, 'changsha'),)
            if tuple_data:
                setInfo_redis(key,tuple_data)
                print(f"ID:{tuple_data[0][0]} 姓名:{tuple_data[0][1]} 年龄:{tuple_data[0][2]} 住址:{tuple_data[0][3]}")
            else:
                print("该学生不存在!")
    return inner
@cache
def getInfo(name):
    cursor.execute("select * from user_info where username=%s;", (name,))
    return cursor.fetchall()

getInfo("sc")
getInfo("sc2")
getInfo("sc3")


